<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Geodesic lines, circles, envelopes in Google Maps</title>
    <meta name="description"
          content="Geodesic lines, circles, envelopes in Google Maps" />
    <meta name="author" content="Charles F. F. Karney">
    <meta name="keywords"
          content="geodesics,
                   geodesic distance,
                   geographic distance,
                   shortest path,
                   direct geodesic problem,
                   inverse geodesic problem,
                   distance and azimuth,
                   distance and heading,
                   range and bearing,
                   geographic circle,
                   geodesic envelope,
                   geodesic astroid,
                   latitude and longitude,
                   Google Maps,
                   WGS84 ellipsoid,
                   GeographicLib" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <!--
        Full URL for latest version of geographiclib.min.js is
        https://geographiclib.sourceforge.io/scripts/geographiclib.min.js
        URL for a specific version is, for example,
        https://geographiclib.sourceforge.io/scripts/geographiclib-1.45.min.js
      -->
    <script type="text/javascript" src="geographiclib.min.js">
    </script>
    <!--
        This API key is restricted to geographiclib.sourceforge.io and
        geographiclib.sourceforge.net.  If you want to deploy this
        facility or one based on it on another computer, that you will
        need to acquire your own API key from Google, see
        https://developers.google.com/maps/documentation/javascript/get-api-key
      -->
    <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC5ITbit5GimGMxQLncpqetCn1QR-sbW_g">
    </script>
    <script type="text/javascript">
"use strict";

var geod = GeographicLib.Geodesic.WGS84,
    dms = GeographicLib.DMS,
    geodesic, circle, envelope, map;

(function(g) {
  "use strict";

  /*
   * split a geodesic line into k approximately equal pieces which are no
   * longer than about ds12 (but k cannot exceed maxk, default 20), and returns
   * an array of length k + 1 of objects with fields lat, lon, azi.
   */
  g.Geodesic.prototype.Path =
    function(line, ds12, maxk) {
      var k, points, da12, vals, i;
      if (!maxk) maxk = 20;
      if (!(ds12 > 0))
        throw new Error("ds12 must be a positive number");
      k = Math.max(1, Math.min(maxk, Math.ceil(Math.abs(line.s13) / ds12)));
      points = new Array(k + 1);
      da12 = line.a13 / k;
      for (i = 0; i <= k; ++i) {
        vals = line.ArcPosition(i * da12);
        points[i] = {lat: vals.lat2, lon: vals.lon2, azi: vals.azi2};
      }
      return points;
    };

  /*
   * return the geodesic circle of radius s12 centered on the point lat1,
   * lon1.  k equally spaced azimuths starting at azi1 are computed.  This
   * returns an array of k + 1 points with fields lat and lon (with the
   * first and last points matching).
   */
  g.Geodesic.prototype.Circle = function(lat1, lon1, azi1, s12, k) {
    var points, vals, i, azi1a;
    if (!(Math.abs(lat1) <= 90))
      throw new Error("lat1 must be in [-90,90]");
    if (!(isFinite(s12)))
      throw new Error("s12 must be a finite number");
    if (!k || k < 4) k = 24;
    points = new Array(k + 1);
    for (i = 0; i <= k; ++i) {
      azi1a = azi1 + (k - i) * 360 / k; // Traverse circle counter-clockwise
      vals = this.Direct(lat1, lon1, azi1a, s12, g.LATITUDE | g.LONGITUDE);
      points[i] = {lat: vals.lat2, lon: vals.lon2};
    }
    return points;
  };

  /*
   * returns the ord'th order envelope for geodesics emanating from lat1, lon1.
   * This is located approximately circumference * ord/2 from the point.  Thus
   * odd numbered envelopes are centered at the antipodal point and even number
   * envelopes are centered on the point itself.  This returns an array of k +
   * 1 points with fields lat and lon (with the first and last points
   * matching).
   */
  g.Geodesic.prototype.Envelope = function(lat1, lon1, k, ord) {
    var points, vals, line, s12, j, i, azi1;
    if (!(Math.abs(lat1) <= 90))
      throw new Error("lat1 must be in [-90,90]");
    if (!k || k < 4) k = 24;
    if (!ord) ord = 1;
    points = new Array(k + 1);
    for (i = 0; i <= k; ++i) {
      azi1 = -180 + i * 360 / k;
      line = this.Line(lat1, lon1, azi1,
                       g.LATITUDE | g.LONGITUDE | g.DISTANCE_IN |
                       g.DISTANCE | g.REDUCEDLENGTH | g.GEODESICSCALE);
      vals = line.ArcPosition(180 * ord,
                              g.DISTANCE | g.REDUCEDLENGTH | g.GEODESICSCALE);
      j = 0;
      while (true) {
        // Solve m12(s12) = 0 by Newton's method using dm12/ds12 = M21
        s12 = vals.s12 - vals.m12/vals.M21;
        if (Math.abs(vals.m12) < line._a * g.tol2_ * 0.1 || ++j > 10)
          break;
        vals = line.Position(s12,
                             g.DISTANCE | g.REDUCEDLENGTH | g.GEODESICSCALE);
      }
      vals = line.Position(s12, g.LATITUDE | g.LONGITUDE);
      points[i] = {lat: vals.lat2, lon: vals.lon2};
    }
    return points;
  };

})(GeographicLib.Geodesic);

function initialize() {
  var i,
      mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(41.3, -5.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      },
      geodesicOptions = {
        strokeColor: '#0000FF',
        strokeOpacity: 1,
        strokeWeight: 3,
        geodesic: true
      },
      circleOptions = {
        strokeColor: '#00FF00',
        strokeOpacity: 1,
        strokeWeight: 3,
        geodesic: true
      },
      envelopeOptions = {
        strokeColor: '#FF0000',
        strokeOpacity: 1,
        strokeWeight: 3,
        geodesic: true
      };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  geodesic = new google.maps.Polyline(geodesicOptions);
  geodesic.setMap(map);

  circle = new google.maps.Polyline(circleOptions);
  circle.setMap(map);

  envelope = new Array(4);
  for (i = 0; i < 4; ++i) {
    envelope[i] = new google.maps.Polyline(envelopeOptions);
    envelope[i].setMap(map);
  }
};

function formatpoint(lat, lon, azi, dmsformat, prec) {
  "use strict";
  var trail;
  prec += 5;
  if (dmsformat) {
    trail = prec < 2 ? dms.DEGREE :
      (prec < 4 ? dms.MINUTE : dms.SECOND);
    prec = prec < 2 ? prec : (prec < 4 ? prec - 2 : prec - 4);
    return (dms.Encode(lat, trail, prec, dms.LATITUDE) + " " +
            dms.Encode(lon, trail, prec, dms.LONGITUDE) + " " +
            dms.Encode(azi, trail, prec, dms.AZIMUTH));
  } else {
    return (lat.toFixed(prec) + " " +
            lon.toFixed(prec) + " " +
            azi .toFixed(prec));
  }
};

function GeodesicInverse(input) {
  "use strict";
  var result = {},
      t, p1, p2, line, v;
  try {
    // Input is a blank-delimited line: lat1 lon1 lat2 lon2
    t = input;
    t = t.replace(/^\s+/,"").replace(/\s+$/,"").split(/[\s,]+/,6);
    if (t.length != 4)
      throw new Error("Need 4 input items");
    p1 = GeographicLib.DMS.DecodeLatLon(t[0], t[1]);
    p2 = GeographicLib.DMS.DecodeLatLon(t[2], t[3]);
    line = geod.InverseLine(p1.lat, p1.lon, p2.lat, p2.lon);
    result.status = "OK";
    v = line.ArcPosition(line.a13);
    result.p1 = formatpoint(v.lat1, v.lon1, v.azi1, true, 0);
    result.p2 = formatpoint(v.lat2, v.lon2, v.azi2, true, 0);
    result.s12 = line.s13.toFixed(0);
    draw(line, v.lat2, v.lon2);
  }
  catch (e) {
    result.status = "ERROR: " + e.message;
    result.p1 = "";
    result.p2 = "";
    result.s12 = "";
  }
  return result;
};

function GeodesicDirect(input) {
  "use strict";
  var result = {},
      t, p1, p2, azi1, s12, line, v;
  try {
    // Input is a blank-delimited line: lat1 lon1 azi1 s12
    t = input;
    t = t.replace(/^\s+/,"").replace(/\s+$/,"").split(/[\s,]+/,6);
    if (t.length != 4)
      throw new Error("Need 4 input items");
    p1 = GeographicLib.DMS.DecodeLatLon(t[0], t[1]);
    azi1 = GeographicLib.DMS.DecodeAzimuth(t[2]);
    s12 = parseFloat(t[3]);
    line =  geod.DirectLine(p1.lat, p1.lon, azi1, s12);
    result.status = "OK";
    v = line.ArcPosition(line.a13);
    result.p1 = formatpoint(v.lat1, v.lon1, v.azi1, true, 0);
    result.p2 = formatpoint(v.lat2, v.lon2, v.azi2, true, 0);
    result.s12 = line.s13.toFixed(0);
    draw(line, v.lat2, v.lon2);
  }
  catch (e) {
    result.status = "ERROR: " + e.message;
    result.p1 = "";
    result.p2 = "";
    result.s12 = "";
  }
  return result;
};

function draw(line, lat2, lon2) {
  "use strict";
  var points = geod.Path(line, 100000, 100),
      i, k, path, v;
  clearPaths();

  path = geodesic.getPath();
  for (k = 0; k < points.length; ++k)
    path.push(new google.maps.LatLng(points[k].lat, points[k].lon));
  points = geod.Circle(line.lat1, line.lon1, line.azi1, line.s13, 72);
  path = circle.getPath();
  for (k = 0; k < points.length; ++k)
    path.push(new google.maps.LatLng(points[k].lat, points[k].lon));
  for (i = 0; i < 4; ++i) {
    points = geod.Envelope(line.lat1, line.lon1, 72, i+1);
    path = envelope[i].getPath();
    for (k = 0; k < points.length; ++k)
      path.push(new google.maps.LatLng(points[k].lat, points[k].lon));
  }
  map.panTo(new google.maps.LatLng(lat2, lon2));
};

function clearPaths() {
  "use strict";
  var i,
      cPath = geodesic.getPath();
  while (cPath.getLength()) cPath.pop();
  cPath = circle.getPath();
  while (cPath.getLength()) cPath.pop();
  for (i = 0; i < 4; ++i) {
    cPath = envelope[i].getPath();
    while (cPath.getLength()) cPath.pop();
  }
};
    </script>
  </head>
  <body onload="initialize()">
    <div id="map-canvas"
         style="position:relative; border: 1px solid black; width:99.5%;
         height:72%;">
    </div>
    <div>
      <p>
        &nbsp;Direct:&nbsp;&nbsp;
        <input id="inputb" size=60 value="41°19'S 174°49'E 135° 60000e3" />
        <input type="button" value="compute"
               onclick="var t = GeodesicDirect(document.getElementById('inputb').value);
                        document.getElementById('status').value = t.status;
                        document.getElementById('p1').value = t.p1;
                        document.getElementById('p2').value = t.p2;
                        document.getElementById('s12').value = t.s12;" />
      </p>
      <p>
        &nbsp;Inverse:
        <input id="inputa" size=60 value="41°19'S 174°49'E 40°58'N 5°30'W" />
        <input type="button" value="compute"
               onclick="var t = GeodesicInverse(document.getElementById('inputa').value);
                        document.getElementById('status').value = t.status;
                        document.getElementById('p1').value = t.p1;
                        document.getElementById('p2').value = t.p2;
                        document.getElementById('s12').value = t.s12;" />
      </p>
      <p>
        &nbsp;lat1 lon1 azi1: <input type="text" "readonly" id="p1" size=60>
      </p>
      <p>
        &nbsp;lat2 lon2 azi2: <input type="text" "readonly" id="p2" size=60>
      </p>
      <p>
        &nbsp;s12: <input type="text" "readonly" id="s12" size=20>
        &nbsp;&nbsp; status: <input "readonly" id="status" size=30>
        &nbsp;&nbsp;
        <a href="geod-google-instructions.html"><b>INSTRUCTIONS</b></a>
        (v<script type="text/javascript">
          document.write(GeographicLib.Constants.version_string);
        </script>)
      </p>
  </div>
  </body>
</html>
